"use client";

import { useState, useRef, ChangeEvent } from "react";
import { UploadCloud, Wand2, Image as ImageIconLucide, AlertTriangle, CheckCircle, Loader2, Sparkles, HelpCircle } from "lucide-react";
import Image from "next/image";
import { AppItem } from "@/app/mockData";

interface StableDiffusionSimulationProps {
  app: AppItem;
}

const StableDiffusionSimulation = ({ app }: StableDiffusionSimulationProps) => {
  const [prompt, setPrompt] = useState("");
  const [uploadedImage, setUploadedImage] = useState<string | null>(null);
  const [generatedImage, setGeneratedImage] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<"txt2img" | "img2img">("txt2img");

  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleImageUpload = (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      if (file.size > 5 * 1024 * 1024) { // 5MB limit
        setError("图片文件不能超过5MB。");
        setUploadedImage(null);
        return;
      }
      if (!["image/jpeg", "image/png", "image/webp"].includes(file.type)) {
        setError("仅支持上传 JPG, PNG, WebP 格式的图片。");
        setUploadedImage(null);
        return;
      }
      setError(null);
      const reader = new FileReader();
      reader.onloadend = () => {
        setUploadedImage(reader.result as string);
      };
      reader.readAsDataURL(file);
      setActiveTab("img2img"); // Switch to img2img tab when image is uploaded
    }
  };

  const handleGenerate = async () => {
    if (activeTab === "txt2img" && !prompt.trim()) {
      setError("请输入文本提示词。");
      return;
    }
    if (activeTab === "img2img" && !uploadedImage) {
      setError("请先上传一张图片。");
      return;
    }
    setError(null);
    setIsLoading(true);
    setGeneratedImage(null);

    // Simulate generation delay
    await new Promise(resolve => setTimeout(resolve, 2000 + Math.random() * 2000));

    // Simulate a successful generation with a placeholder image
    // In a real app, this would be the result from an API call
    // For demonstration, we'll use a placeholder or one of the app's images if available
    const placeholderImageUrl = app.imageUrl || "/placeholder-images/aetherbrush.png"; // Fallback
    setGeneratedImage(placeholderImageUrl); 
    setIsLoading(false);
  };
  
  const handleExamplePrompt = (example: string) => {
    setPrompt(example);
    setActiveTab("txt2img");
  };

  return (
    <div className="bg-gray-800 shadow-xl rounded-lg p-6">
      <div className="mb-4 border-b border-gray-700">
        <nav className="-mb-px flex space-x-6" aria-label="Tabs">
          <button
            onClick={() => setActiveTab("txt2img")}
            className={`whitespace-nowrap pb-3 px-1 border-b-2 font-medium text-sm transition-colors ${
              activeTab === "txt2img"
                ? "text-indigo-400 border-indigo-500"
                : "text-gray-400 border-transparent hover:text-gray-200 hover:border-gray-500"
            }`}
          >
            文生图 (Text-to-Image)
          </button>
          <button
            onClick={() => setActiveTab("img2img")}
            className={`whitespace-nowrap pb-3 px-1 border-b-2 font-medium text-sm transition-colors ${
              activeTab === "img2img"
                ? "text-indigo-400 border-indigo-500"
                : "text-gray-400 border-transparent hover:text-gray-200 hover:border-gray-500"
            }`}
          >
            图生图 (Image-to-Image)
          </button>
        </nav>
      </div>

      {activeTab === "img2img" && (
        <div className="mb-6 p-4 border border-dashed border-gray-600 rounded-lg bg-gray-800/50">
          <label
            htmlFor="imageUpload"
            className="flex flex-col items-center justify-center w-full h-48 cursor-pointer hover:bg-gray-700/50 transition-colors rounded-md"
          >
            {uploadedImage ? (
              <div className="relative w-full h-full">
                <Image src={uploadedImage} alt="Uploaded preview" layout="fill" objectFit="contain" className="rounded-md" />
                <button 
                  onClick={(e) => { e.stopPropagation(); setUploadedImage(null); if(fileInputRef.current) fileInputRef.current.value = "";}}
                  className="absolute top-2 right-2 bg-red-600 hover:bg-red-700 text-white p-1.5 rounded-full text-xs z-10"
                  title="移除图片"
                >
                  &#x2715;
                </button>
              </div>
            ) : (
              <>
                <UploadCloud className="w-10 h-10 text-gray-500 mb-2" />
                <p className="mb-1 text-sm text-gray-400"><span className="font-semibold">点击上传图片</span> 或拖拽到此处</p>
                <p className="text-xs text-gray-500">支持 JPG, PNG, WebP (最大 5MB)</p>
              </>
            )}
          </label>
          <input id="imageUpload" type="file" className="hidden" onChange={handleImageUpload} accept="image/jpeg,image/png,image/webp" ref={fileInputRef} />
        </div>
      )}

      <div className="mb-4">
        <label htmlFor="prompt" className="block text-sm font-medium text-gray-300 mb-1.5">提示词 (Prompt)</label>
        <textarea
          id="prompt"
          rows={3}
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          placeholder={activeTab === "img2img" ? "描述您想如何变换上传的图片，或留空以进行风格迁移..." : "例如：一只穿着宇航服的猫在月球上弹吉他，数字艺术风格..."}
          className="w-full p-3 bg-gray-700 text-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-shadow shadow-inner resize-none custom-scrollbar"
        />
      </div>
      
      {app.sdPromptExamples && app.sdPromptExamples.length > 0 && (
        <div className="mb-4 flex flex-wrap gap-2">
          <span className="text-sm text-gray-400 self-center mr-1">或试试:</span>
          {app.sdPromptExamples.slice(0, 3).map((example, index) => (
            <button
              key={index}
              onClick={() => handleExamplePrompt(example)}
              className="px-3 py-1.5 text-xs bg-gray-700 hover:bg-gray-600 text-indigo-300 rounded-full transition-colors flex items-center shadow"
            >
              <HelpCircle size={14} className="mr-1.5 opacity-70" /> 
              {example}
            </button>
          ))}
        </div>
      )}

      {/* Placeholder for advanced parameters - can be expanded later */}
      {/* <div className="mb-4">
        <details className="bg-gray-750 p-3 rounded-lg">
          <summary className="text-sm font-medium text-gray-300 cursor-pointer hover:text-indigo-400">高级参数 (可选)</summary>
          <div className="mt-3 space-y-3">
            <p className="text-xs text-gray-400">此处可添加负面提示词、采样步数、CFG Scale等参数...</p>
          </div>
        </details>
      </div> */}

      <button
        onClick={handleGenerate}
        disabled={isLoading}
        className="w-full flex items-center justify-center p-3 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 text-white rounded-lg disabled:opacity-60 disabled:cursor-not-allowed transition-all shadow-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-gray-800 font-semibold text-base"
      >
        {isLoading ? (
          <><Loader2 className="w-5 h-5 mr-2 animate-spin" /> 正在生成...</>
        ) : (
          <><Wand2 className="w-5 h-5 mr-2" /> 开始生成</>
        )}
      </button>

      {error && (
        <div className="mt-4 p-3 bg-red-800/50 text-red-300 border border-red-700 rounded-lg flex items-center">
          <AlertTriangle className="w-5 h-5 mr-2 flex-shrink-0" />
          <p className="text-sm">{error}</p>
        </div>
      )}

      {generatedImage && !isLoading && (
        <div className="mt-6">
          <h3 className="text-lg font-semibold text-gray-100 mb-3 flex items-center"><Sparkles className="w-5 h-5 mr-2 text-yellow-400"/>生成结果：</h3>
          <div className="bg-gray-700/50 p-2 rounded-lg shadow-inner aspect-square max-w-md mx-auto">
            <Image src={generatedImage} alt="Generated image" width={512} height={512} className="rounded-md object-contain w-full h-full" />
          </div>
        </div>
      )}
      {isLoading && !generatedImage && (
         <div className="mt-6 text-center">
            <div className="inline-block w-10 h-10 border-4 border-indigo-400 border-t-transparent rounded-full animate-spin mb-2"></div>
            <p className="text-sm text-gray-400">AI正在努力创作中，请稍候...</p>
         </div>
      )}

    </div>
  );
};

export default StableDiffusionSimulation;

